from django.db.models import Q
from django.template import *
from l2ldjango.apps.mailmanagement.models import *
from django.middleware import *
from django.contrib.auth.models import User
from django.core.files.base import ContentFile
from django.shortcuts import *
from django.template.loader import get_template
from l2ldjango.apps.usermanagement.models import *
from django.core.mail import send_mail
from django.core.files.uploadedfile import SimpleUploadedFile
from django.middleware import *
from django.core.paginator import Paginator, InvalidPage, EmptyPage
from django.core.mail import send_mail
from l2ldjango.apps.mailmanagement.forms import *
from django.contrib.auth.decorators import login_required

def saveMail__rsapractice(request):
	import rsa
	(pub,pri)=rsa.newkeys(1024)
	#message="This is Mahesh,saying Hello to the world,I am encryted while saving and decryted while retrieving!"
	message="This is Mahes!"
	crypto=rsa.encrypt(message,pub)
	m=mail1()
	m.message=unicode(crypto).decode('utf-8')
	m.public_key=pub
	m.private_key=pri
	mail=m.save()
	variables = RequestContext(request,{'mails':mail})    
	return render_to_response('pages/home.html',variables) 
	#return HttpResponse(crypto)



def Send_contactMail(request):
	if request.method=='POST':
		form = ContactForm(request.POST)
		if form.is_valid():	
			subject="Contact form Details(Windtrader)"
			
			email=request.POST["Email"]
			name=request.POST["Name"]
			if request.POST["Company"]:
				Company=request.POST["Company"]
			else:
				Company = 'none'
			if request.POST["Country"]:
				countryid=request.POST["Country"]
				cntry=country.objects.get(pk=countryid)
				Country=cntry.name
			else:
				Country = 'none'
				
			if request.POST["Name"]:
				Region=request.POST["Region"]
			else:
				Region='none'
			
			message=request.POST["Message"]
			message='%s%s%s%s%s%s%s%s%s%s'%('Name:',name,'  Company:',Company,'  Country:',Country,'  Region:',Region,'  Message:',message)
			send_mail(subject, message, email,['themaheshe1@gmail.com'], fail_silently=False)
			form = ContactForm()
			variables = RequestContext(request,{'classname':'contactus','message':'Mail has successfully sent to the administrator','form':form})
			return render_to_response('mailmanagement/contactus.html',variables)	
			
		else:
			errs=form.errors
			form = ContactForm(request.POST)
			variables = RequestContext(request,{'classname':'contactus','form': form,'message':errs,'csrf_token':csrf.get_token(request)})
			return render_to_response('mailmanagement/contactus.html',variables)	
	else:
		form = ContactForm()
		variables = RequestContext(request,{'classname':'contactus','form': form,'csrf_token':csrf.get_token(request)})
		return render_to_response('mailmanagement/contactus.html',variables)
	
def Send_mail(request):
	if request.method == 'POST':
		mailfrm=mail()
		username=request.user
		mailfrm.mail_from=username
		mail_to_username=request.POST['mail_to']
		usr=User.objects.get(username=mail_to_username)
		mail_to=usr
		subject=request.POST['subject']
		message=request.POST['message']
		if mail_to and subject and message:
			mailfrm.mail_to=mail_to
			mailfrm.mail_subject=subject
			mailfrm.mail_details=message
			if request.POST["msgtype"] == 'True':
				mailfrm.mail_onrecord = True
			else:
				mailfrm.mail_onrecord = False		
			mailfrm.save()
			variables = RequestContext(request,{'message':'Your Mail has successfully been sent,Thank you'})
			return render_to_response('mailmanagement/sendmail_page.html',variables)
		else:
			variables = RequestContext(request,{'form': mailform,'message':'Error Sending Message,Please check the fields correctly'})
			return render_to_response('mailmanagement/sendmail_page.html',variables)	
	else:
		variables = RequestContext(request,{'message':'Compose Mail'})
		return render_to_response('mailmanagement/sendmail_page.html',variables)
		
def Send_mail_public(request,userid):
	if request.method == 'POST':
		mailfrm=mail()
		username=request.user
		mailfrm.mail_from=username
		mail_to_username=request.POST['mail_to']
		usr=User.objects.get(username=mail_to_username)
		mail_to=usr
		subject=request.POST['subject']
		message=request.POST['message']
		if mail_to and subject and message:
			mailfrm.mail_to=mail_to
			mailfrm.mail_subject=subject
			mailfrm.mail_details=message
			if request.POST["msgtype"] == 'True':
				mailfrm.mail_onrecord = True
			else:
				mailfrm.mail_onrecord = False		
			mailfrm.save()			
			return HttpResponse("Your Mail has successfully been sent, Thank you")
		else:
			#variables = RequestContext(request,{'form': mailform,'message':'Error Sending Message,Please check the fields correctly'})
			return HttpResponse("Error Sending Message, Please check the fields correctly")
	else:
		usr = User.objects.get(id=userid)		
		variables = RequestContext(request,{'usr':usr})
		return render_to_response('mailmanagement/sendmail_public.html',variables)

def Reply_mail(request,mailId=''):
	if request.method == 'POST':
		mailfrm=mail()
		username=request.user
		mailfrm.mail_from=username
		mail_to_username=request.POST['mail_to']
		usr=User.objects.get(username=mail_to_username)
		mail_to=usr
		subject="Re: %s"%(request.POST['subject'])
		message=request.POST['message']
		if mail_to and subject and message:
			mailfrm.mail_to=mail_to
			mailfrm.mail_subject=subject
			mailfrm.mail_details=message
			if request.POST["msgtype"] == 'True':
				mailfrm.mail_onrecord = True
			else:
				mailfrm.mail_onrecord = False		
			mailfrm.save()
			variables = RequestContext(request,{'message':'Your Mail has successfully been sent,Thank you'})
			return render_to_response('mailmanagement/sendmail_page.html',variables)
		else:
			variables = RequestContext(request,{'form': mailform,'message':'Error Sending Message,Please check the fields correctly'})
			return render_to_response('mailmanagement/replymail_page.html',variables)	
	else:
		mailinfo = mail.objects.get(id=mailId)
		variables = RequestContext(request,{'message':'Compose Mail','mailinfo':mailinfo})
		return render_to_response('mailmanagement/replymail_page.html',variables)			
		
@login_required
def Inbox_mail(request):
	
	return HttpResponseRedirect('/l2l/messages/')
	
	mailto=request.user.id
  	inbx=mail.objects.filter(mail_to=mailto,mail_status_inbox='ACTIVE').order_by("-mail_sent_date")
	#for pagination
	paginator = Paginator(inbx, 5) # Show 6 mails per page
	try:
		page = int(request.GET.get('page', '1'))
	except ValueError:
		page = 1
	try:
		inboxes = paginator.page(page)
	except (EmptyPage, InvalidPage):
		inboxes = paginator.page(paginator.num_pages)
	
	#for pagination
	
	variables = RequestContext(request,{'message':'Your Mail InBox','inbxmessages':inboxes,'user':request.user})
	#x=loadthemes(request,'mailmanagement/inbox_page.html',variables)
	#return x
	#return render_to_response('mailmanagement/inbox_page.html',variables)
	return render_to_response('mailmanagement/messages.html',variables)
	
@login_required	
def Outbox_mail(request):
	mailfrom=request.user
	outbx=mail.objects.filter(mail_from=mailfrom,mail_status_outbox='ACTIVE').order_by("-mail_sent_date")
	#for pagination
	paginator = Paginator(outbx, 5) # Show 6 mails per page
	try:
		page = int(request.GET.get('page', '1'))
	except ValueError:
		page = 1
	try:
		outboxes = paginator.page(page)
	except (EmptyPage, InvalidPage):
		outboxes = paginator.page(paginator.num_pages)
	
	#for pagination
	variables = RequestContext(request,{'title':'Outbox','message':'Your Mail OutBox','outbxmessages':outboxes})	
	return render_to_response('mailmanagement/outbox_page.html',variables)	

@login_required
def readMailDetails(request,mailID):	
	maildtls=mail.objects.get(pk=mailID)
	variables=RequestContext(request,{'maildtls':maildtls,'user':request.user })
	#x=loadthemes(request,'mailmanagement/readmail.html',variables)
	#return x
	return render_to_response('mailmanagement/readmaildetails.html',variables)	

@login_required
def Read_mail(request,mailID):	
	maildtls=mail.objects.get(pk=mailID)
	if maildtls.mail_to==request.user or maildtls.mail_from==request.user:
		images = ImageGallery.objects.filter(user_id=maildtls.mail_from.id)
		len_images = len(list(images))
		variables=RequestContext(request,{'title':maildtls.mail_subject,'message':'Mail Details','m':maildtls,'user':request.user,'images':images,'len_images':len_images })
		maildtls.is_read=True
		maildtls.save()			
		return render_to_response('mailmanagement/readmail.html',variables)	
	else:
		variables=RequestContext(request,{'title':'Permission Denied.','message':'You are not authorized to read others Mail','user':request.user })
		return render_to_response('pages/success_page.html',variables)	

#without using ajax
def Delete_inboxmail(request):
	if (request.GET['checkbox_name']):
		chks=request.GET['checkbox_name']
		for chk in chks:
			ml=mail.objects.get(pk=chk)
			ml.mail_status_inbox='INACTIVE'
			ml.save()
	
	mailto=request.user
  	inbx=mail.objects.filter(mail_to=mailto,mail_status_inbox='ACTIVE').order_by("mail_sent_date")
	#for pagination
	paginator = Paginator(inbx, 5) # Show 6 ads per page
	try:
		page = int(request.GET.get('page', '1'))
	except ValueError:
		page = 1
	try:
		inboxes = paginator.page(page)
	except (EmptyPage, InvalidPage):
		inboxes = paginator.page(paginator.num_pages)
	
	#for pagination
	
	variables = RequestContext(request,{'title':'Inbox','message':'Your Mail InBox','inbxmessages':inboxes})
	return render_to_response('mailmanagement/inbox_page.html',variables)


#using ajax
def Deleting_inboxmail(request):
	if (request.POST['chk_delete']):
		#chks=request.GET['chk_delete']
		chks=request.POST.getlist(u'chk_delete')
		for chk in chks:
			ml=mail.objects.get(pk=chk)
			ml.mail_status_inbox='INACTIVE'
			ml.save()
					
		return Inbox_mail(request)
	else:
		return Inbox_mail(request)

def Deleting_outboxmail(request):
	if (request.POST['chk_delete']):
		chks=request.POST.getlist(u'chk_delete')
		for chk in chks:
			ml=mail.objects.get(pk=chk)
			ml.mail_status_outbox='INACTIVE'
			ml.save()					
		return Outbox_mail(request)
	else:
		return Outbox_mail(request)
	
#using ajax
def Deleting_inboxmail__old(request):
	if (request.GET['chk_delete']):
		chks=request.GET['chk_delete']
		#chks=request.POST.getlist(u'chk_delete')
		return HttpResponse(chks)
		for chk in chks:
			ml=mail.objects.get(pk=chk)
			ml.mail_status_inbox='INACTIVE'
			ml.save()
					
		return HttpResponse('true')
	else:
		return HttpResponse('false')


	
def Delete_individual_mail(request,mailID,msgtype):
	ml=mail.objects.get(pk=mailID)
	
	if (msgtype=='inbox'):
		ml.mail_status_inbox='INACTIVE'
		ml.save()
		return HttpResponseRedirect('/mailmanagement/inbox/')

	else:	
		ml.mail_status_outbox='INACTIVE'
		ml.save()
		#mailfrom='%s%s'%(request.user,'@windtrader.com')
		#outbx=mail.objects.filter(mail_from=mailfrom,mail_status_outbox='ACTIVE',mail_exchange_to_sender='OUTBOX').order_by("-mail_sent_date")
		return HttpResponseRedirect('/mailmanagement/inbox/')	


def MovetoDraft(request,mailID,msgtype):
	ml=mail.objects.get(pk=mailID)
	if (msgtype=='inbox'):
		ml.mail_exchange_to_receiver='DRAFT'
		ml.save()
		mailto='%s%s'%(request.user,'@windtrader.com')
		inbx=mail.objects.filter(mail_to=mailto,mail_status_inbox='ACTIVE',mail_exchange_to_receiver='INBOX').order_by("mail_sent_date")
		variables = RequestContext(request,{'message':'Mail Successfully Moved to Draft','inbxmessages':inbx,'user':request.user})
		#x=loadthemes(request,'mailmanagement/inbox_page.html',variables)
		return render_to_response('mailmanagement/inbox_page.html',variables)
	else:	
		ml.mail_exchange_to_sender='DRAFT'
		ml.save()
		mailfrom='%s%s'%(request.user,'@windtrader.com')
		outbx=mail.objects.filter(mail_from=mailfrom,mail_status_outbox='ACTIVE',mail_exchange_to_sender='OUTBOX').order_by("-mail_sent_date")
		variables = RequestContext(request,{'message':'Mail Successfully Moved to Draft','outbxmessages':outbx,'user':request.user})	
		#x=loadthemes(request,'mailmanagement/outbox_page.html',variables)
		return render_to_response('mailmanagement/outbox_page.html',variables)
		
def Draft_mail(request):
	mailfrm='%s%s'%(request.user,'@windtrader.com')
	drafts=mail.objects.filter(
		Q(mail_from=mailfrm,mail_status_outbox='ACTIVE',mail_exchange_to_sender='DRAFT')|
		Q(mail_to=mailfrm,mail_status_inbox='ACTIVE',mail_exchange_to_receiver='DRAFT')
		)
	#drafts=mail.objects.filter(mail_from=mailfrom)	
	variables = RequestContext(request,{'message':'Your Messages in DraftInBox','drafts':drafts,'user':request.user})	
	#x=loadthemes(request,'mailmanagement/draft_page.html',variables)
	#return x
	return render_to_response('mailmanagement/draft_page.html',variables)
	
def Agree(request):	
	m = mail.objects.get(pk=request.POST["mailId"])
	m.is_agreed = True
	m.save()
	return HttpResponse("Flag updated successfully")
